package com.toocms.jinjuhang.ui.mine.receiver_address

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.*
import com.toocms.jinjuhang.data.center.AddressDetailsData
import com.toocms.jinjuhang.data.system.RegionItemData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger
import com.toocms.tab.bus.event.SingleLiveEvent
import com.toocms.tab.widget.picker.OptionsPickerView
import com.toocms.tab.widget.picker.builder.OptionsPickerBuilder

class EditReceiverAddressModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {
    var optionsPickerView: (OptionsPickerView<RegionItemData>)? = null

    val dataObservableField = ObservableField(AddressDetailsData())
    val daiShouObservableField = ObservableBoolean()

    val addressChangeSingleLiveEvent = SingleLiveEvent<String>()

    val adrId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_ADR_ID) ?: ""
    }

    val locationClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
//        TabMapApi.getChoosingApi().startNearPoiPageForResult(this) { poiItem ->
//            dataObservableField.get()?.apply {
//                this.province_name = poiItem.provinceName
//                this.city_name = poiItem.cityName
//                this.district_name = poiItem.adName
//                this.district_id = poiItem.adCode
//                this.latitude = poiItem.latLonPoint.latitude.toString()
//                this.longitude = poiItem.latLonPoint.longitude.toString()
//                dataObservableField.notifyChange()
//                addressChangeSingleLiveEvent.value = poiItem.title
//            }
//        }
        val localRegion = Region.localRegion
        if (null == localRegion) {
            showToast("正在获取地址列表,请稍后再试")
            return@BindingAction
        }

        val province = localRegion?.province ?: ArrayList()
        val city = localRegion?.city ?: ArrayList()
        val district = localRegion?.district ?: ArrayList()
        optionsPickerView = OptionsPickerBuilder(
            ActivityUtils.getTopActivity()
        ) { view, options1, options2, options3 ->
            dataObservableField.get()?.apply {
                this.province_name = province[options1].region_name
                this.city_name = city[options1][options2].region_name
                this.district_name = district[options1][options2][options3].region_name
                this.district_id = district[options1][options2][options3].id
//                this.latitude = poiItem.latLonPoint.latitude.toString()
//                this.longitude = poiItem.latLonPoint.longitude.toString()
                dataObservableField.notifyChange()
            }
            optionsPickerView?.dismiss()
            return@OptionsPickerBuilder true
        }.run {
            setTitleText("选择地址")
            setDividerColor(0x00000000)
            setLabels("", "", "")
            build<RegionItemData>()
        }.apply {
            setPicker(
                province,
                city,
                district
            )
            show()
        }
    })

    val setDefaultLocationClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        dataObservableField.get()?.apply {
            is_default =
                if (Constants.Extra.DEFAULT_ADDRESS_YES.equals(is_default)) Constants.Extra.DEFAULT_ADDRESS_NO
                else Constants.Extra.DEFAULT_ADDRESS_YES
            dataObservableField.notifyChange()
        }
    })

    val setDaiShouLocationClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        daiShouObservableField.set(!daiShouObservableField.get())
    })

    val saveClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        dataObservableField.get()?.apply {
            if (!daiShouObservableField.get() && TextUtils.isEmpty(district_id)) {
                showToast(R.string.str_no_selected_address_hint)
                return@BindingAction
            }
            val params = mutableMapOf<String, String?>()
            params["member_id"] = UserRepository.user.member_id
            params["adr_id"] = adr_id
            params["use_organ"] = when (daiShouObservableField.get()) {
                true -> "1"
                false -> "0"
            }
            params["contacts"] = contacts
            params["mobile"] = mobile
            params["latitude"] = latitude
            params["longitude"] = longitude
            params["province_name"] = when (daiShouObservableField.get()) {
                true -> "机构代收省"
                false -> province_name
            }
            params["city_name"] = when (daiShouObservableField.get()) {
                true -> "机构代收市"
                false -> city_name
            }
            params["district_name"] = when (daiShouObservableField.get()) {
                true -> "机构代收区"
                false -> district_name
            }
            params["district_id"] = when (daiShouObservableField.get()) {
                true -> "100000"
                false -> district_id
            }
            params["address"] = when (daiShouObservableField.get()) {
                true -> "机构代收详细地址"
                false -> address
            }
            params["is_default"] = is_default
            requestData(Urls.Center.UPD_ADDRESS,
                params,
                resultClass = String::class.java,
                result = {
                    showToast(it)
                    Messenger.getDefault()
                        .sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ADDRESS)
                    this@EditReceiverAddressModel.finishFragment()
                })
        }
    })

    init {
        if (!TextUtils.isEmpty(adrId)) {
            val params = mutableMapOf<String, String?>()
            params["member_id"] = UserRepository.user.member_id
            params["adr_id"] = adrId
            requestData(Urls.Center.ADDRESS,
                params,
                resultClass = AddressDetailsData::class.java,
                result = {
                    dataObservableField.set(it)
                    daiShouObservableField.set(it.use_organ.equals("1"))
                })
        }

//        OptionsPickerBuilder(application,object :OnOptionsSelectListener{
//            override fun onOptionsSelect(
//                view: View?,
//                options1: Int,
//                options2: Int,
//                options3: Int
//            ): Boolean {
//                return true
//            }
//
//        }).build<String>()
//            .setPicker()
    }


}